﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.WebPages;
using WebSite.Models;

namespace WebSite.Controllers
{
    public class MemberController : Controller
    {
        // GET: Member
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult GetList(string type)
        {
            using (var context = new DefaultContext())
            {
                var list = context.MemberSet.AsQueryable().Where(p =>string.IsNullOrEmpty(type) || p.Type == type).Select(p => new
                {
                    p.Age,
                    p.ID,
                    p.Name
                }).ToList();
                return Json(list);
            }
        }
        public ActionResult Add(string name, string age)
        {
            var callback = Request["CallBack"];
            int nage;
            if (!int.TryParse(age, out nage))
            {
                return Json(0);
            }
            if (name.IsEmpty())
            {
                return Json(0);
            }
            using (var context = new DefaultContext())
            {
                var member = context.MemberSet.Add(new Member
                {
                    Name = name,
                    Age = nage
                });
                context.SaveChanges();
                if (member.ID == null)
                {
                    return Json(0);
                }
            }
            return Json(1);
        }

        public ActionResult Update(int ID, string Name, int Age)
        {
            using (var context = new DefaultContext())
            {
                var member = context.MemberSet.Find(ID);
                if (member == null) return Json(0);
                member.Age = Age;
                member.Name = Name;
                var it = context.SaveChanges();
                if (it != 1)
                {
                    return Json(0);
                }
                return Json(1);
            }
        }

        public ActionResult Delete(int ID)
        {
            using (var context = new DefaultContext())
            {
                var member = context.MemberSet.Find(ID);
                if (member == null) return Json(0);
                var dt = context.MemberSet.Remove(member);
                context.SaveChanges();
                return Json(1);
            }
        }

        public new ActionResult Json(object data)
        {
            var name = Request["CallBack"];
            return Content($"{name}({Newtonsoft.Json.JsonConvert.SerializeObject(data)})");
        }
    }
}